% Create Fresh Environment
close all
clear all
clc

% Define Constants
F = 50;                 % Original Frequency
Fs = 600;               % Sampling Frequency
Ts = 1/Fs;              % Sampling Period
Tprec = 1/100000;       % Continous Time Precision
t = 0:Tprec:1-Tprec;    % Time Vector
Amp = 2;                % Signal Amplitude
Ni = 0.4;               % Noise Power

%Contious Time, Original Function
N0 = Ni*randn(size(t));
X0 = Amp*sin(2*pi*F*t)+ N0;

% Plot Continous Plot
figure(1);
subplot(2,1,1);
plot(t,X0);
axis([0 0.1 -2 2]);
title(sprintf('Continous Time X(t) = %dSin(2*pi*%d*t)',Amp,F));
xlabel('Time (sec)');
ylabel('Amplitude');

% Number of samples from COnt. Time Being used, based on Ts
tHat = t(1:length(t)*Ts:end);

%length(n)-1 --> Keep matrix sizes equal
n = 0:length(tHat)-1;

%Discrete Representation of the time vector
%Dependent on the sampling period which determines the # of Samples(n)
NTs = n*Ts;
% Noise N[n]
Nn = Ni*randn(size(n));
xNTs = Amp*sin(2*pi*F*NTs)+Nn;

% Plot Discrete Plot
% Add Stem Plot Over Continous
hold on;
stem(tHat,xNTs,'MarkerSize',5,'Marker','.','Color','r');
hold off;

% Plot resulting Graph
subplot(2,1,2);
plot(n,xNTs);
axis([0 60 -2 2]);
title(sprintf('Continous Time X[n] = %dSin(2*pi*%d*n*Ts)',Amp,F));
xlabel('Time (samples)');
ylabel('Amplitude');

% Length of Signal For Window
L = length(xNTs);

% Length of FFT
nFFT = 1024;

X = transpose(xNTs).*hanning(L);

%Prepare FFT
Xdft = fft(X,nFFT)/L;
%Calc. Magnitude
Xdft = abs(Xdft);
% All frequencies except zero and the Nyquist
Xdft = Xdft (1:nFFT/2+1);
Xdft (2:end-1) = 2* Xdft(2:end-1);

% Frequency Axis
f = Fs/2*linspace(0,1,nFFT/2+1); 

%Plot FFT
figure(2);
plot(f,2*Xdft);
axis ([30 70 0 2]);
title(sprintf('Amplitude Spectrum with Hann Window. N=%d',nFFT));
xlabel('Frequency (Hz)with hanning window'); 
ylabel('|Y(f)|');
